from flask import render_template, request

from app.software import soft_bp
from app.models import Software


@soft_bp.route('/')
def software_management():
    if request.args.get('q'):
        q = request.args.get('q')
        software = Software.query.filter(Software.name.like('%{}%'.format(q))).all()
        result = {}
        for each in software:
            if result.get(each.name):
                result.get(each.name).append(software_schema(each))
            else:
                result[each.name] = [software_schema(each)]
        return render_template('panel/software.html', software=result, q=q)
    name_column = Software.query.with_entities(Software.name).distinct().all()
    name_list = []
    for item in name_column:
        name_list.append(item.name)
    result = {}
    result = result.fromkeys(name_list)
    for each in result:
        software = Software.query.filter_by(name=each)
        result[each] = [software_schema(single_version) for single_version in software]
    return render_template('panel/software.html', software=result)


def software_schema(software):
    return {
        'id': software.id,
        'name': software.name,
        'status': software.status,
        'version': software.version,
        'path': software.path,
        'slug': software.slug,
        'describe': software.describe
    }


